package com.aac.rabbitapi.controller;

import com.aac.rabbitapi.constant.Queues;
import com.aac.rabbitapi.consumer.ResponseMapConsumer;
import com.aac.rabbitapi.producer.RequestMapProducer;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/rfc")
public class BpmToRfcController {

    @Autowired
    private RequestMapProducer requestMapProducer;

    @Autowired
    private ResponseMapConsumer responseMapConsumer;

    @RequestMapping(value = "/json")
    public Map<String, Object> getResponseMap(@RequestBody Map<String, Object> requestMap) throws InterruptedException {
        String requestID = UUID.randomUUID().toString();
        int reqQNo = RandomUtils.nextInt(1, 6);
        requestMap.put("requestID", requestID);
        requestMap.put("reqQNo", reqQNo);
        String requestJson = JSON.toJSONString(requestMap);
        // for rfc consumer based on springboot
        requestMapProducer.sendRequestMap(Queues.REQUEST_QUEUE + reqQNo, requestMap);
        Map<String, Object> responseMap = responseMapConsumer.getResponseMap();
        // 不断获取@RabbitListener监听到的响应数据，响应数据不为NULL时退出循环。
        while (responseMap == null) {
            Thread.sleep(100);
            responseMap = responseMapConsumer.getResponseMap();
        }
        String responseID = (String) responseMap.get("responseID");
        int resQNo = (int) responseMap.get("resQNo");
        // 不断获取@RabbitListener监听到的响应数据，当标记值相同时退出循环。
        while (!(StringUtils.equals(requestID, responseID) && reqQNo == resQNo)) {
            Thread.sleep(100);
            responseMap = responseMapConsumer.getResponseMap();
            responseID = (String) responseMap.get("responseID");
            resQNo = (int) responseMap.get("resQNo");
        }
        return responseMap;
    }

}
